package com.ahui.server.controller;

import com.ahui.server.pojo.Admin;
import com.ahui.server.pojo.AdminLoginParam;
import com.ahui.server.pojo.RespBean;
import com.ahui.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录
 *
 * @author ahui on 2021/4/22
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),request);
    }


    /**
     * 登录之后把登录用户设置到全局中，可以通过Security的Principal获取到对象
     * @return
     */
    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        //判断是否为空，如果是空的，则说明登录有问题，则不返回任何信息
        if (null==principal){
            return null;
        }
        //principal.getName()获取到的就是username
        String username = principal.getName();
        //通过username获取到完整的用户对象
        Admin admin =  adminService.getAdminByUserName(username);
        //为保证数据安全，返回的admin对象，通常把密码设置为null
        admin.setPassword(null);
        return admin;
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功！");
    }
}
